package com.liveinstars.im.core.service.impl;

import com.liveinstars.api.im.vo.CandyBoxVO;
import com.liveinstars.im.core.service.CandyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * @author: zhouze
 * @date: 2020/3/20
 */
@Service("candyService")
public class CandyServiceImpl implements CandyService {

    private final static Logger logger = LoggerFactory.getLogger(CandyServiceImpl.class);


    private final static String CANDY_KIDS_QUEUE = "CANDY_KIDS_QUEUE";

    @Override
    public CandyBoxVO createCandyBox(Long userId, CandyBoxVO vo) {
        return null;
    }

    @Override
    public CandyBoxVO getCandy(Long userId, Long candy) {
        return null;
    }

    @Override
    public CandyBoxVO getCandyBoxDetail(Long candyBoxId) {
        return null;
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public CandyBoxVO createCandyBox(Long userId, CandyBoxVO vo) {
//        vo.createCheck();
//        if (vo.getCandyNum() < vo.getUserNum()) {
//            throw new IMRuntimeException(IMExceptionEnum.CANDY_NUM_LESS_THEN_USER_NUM);
//        }
//        CandyBoxDTO candyBoxDTO = new CandyBoxDTO(vo);
//        candyBoxDTO.getCandyBox().setCreateUserId(userId);
//        candyBoxManager.add(candyBoxDTO.getCandyBox());
//        if (candyBoxDTO.getCandyBoxVO().getCandyType().equals(CandyBoxDTO.GOLD_CANDY)) {
//            GoldWithHoldReq goldWithHoldReq = new GoldWithHoldReq();
//            goldWithHoldReq.setType(GoldWithHoldEnum.RED_PACKET.withHoldType);
//            goldWithHoldReq.setOrderNo(candyBoxDTO.getCandyBox().getId().toString());
//            goldWithHoldReq.setAmount(candyBoxDTO.getCandyBox().getCandyNum().intValue());
//            goldWithHoldReq.setUid(userId);
//            Result<Long> goldHoldResult = goldApi.goldWithHold(goldWithHoldReq);
//            if(! goldHoldResult.getCode().equals(Result.SUCCESS)) {
//                logger.error("预扣金币异常");
//                throw new IMRuntimeException(IMExceptionEnum.GOLD_IS_NOT_ENOUGH);
//            }
//        } else {
//            logger.error("糖果类型异常：candyType:{}", vo.getCandyType());
//            throw new IMRuntimeException(IMExceptionEnum.CANDY_TYPE_ERROR);
//        }
//        try {
//            List<CandyKidsRecord> candyKidsRecordList = candyBoxDTO.initKidsList();
//            candyKidsRecordManager.batchInsert(candyKidsRecordList);
//            candyBoxDTO.getCandyBoxVO().setId(candyBoxDTO.getCandyBox().getId());
//            ImGetUserInfo userInfo = imUserCentreApi.imGetUserInfo(userId);
//            ChatMessage candyMessage = candyBoxDTO.createCandyMessage(userInfo, messageService.getMsgId());
//            messageService.sendMessage(candyMessage);
//        } catch (Exception e) {
//            try {
//                CancelWithHoldReq cancelWithHoldReq = new CancelWithHoldReq();
//                cancelWithHoldReq.setOrderNo(candyBoxDTO.getCandyBox().getId().toString());
//                cancelWithHoldReq.setType(GoldWithHoldEnum.RED_PACKET.withHoldType);
//                cancelWithHoldReq.setUid(userId);
//                goldApi.cancelWithHold(cancelWithHoldReq);
//            } catch (Exception e1) {
//                logger.error("取消金币预扣失败！candyBoxId: {}, errorMsg: {}", candyBoxDTO.getCandyBox().getId().toString(), e1.getMessage(), e1);
//            }
//            if (e instanceof IMRuntimeException) {
//                throw new IMRuntimeException(((IMRuntimeException) e).getCode(), e.getMessage());
//            } else {
//                throw new IMRuntimeException(IMExceptionEnum.CANDY_CREATE_ERROR);
//            }
//        }
//        return candyBoxDTO.getCandyBoxVO();
//    }
//
//    @Override
//    public CandyBoxVO getCandy(Long userId, Long candyBoxId) {
//        CandyBox candyBox = candyBoxManager.getById(candyBoxId);
//        if (candyBox.getStatus().equals(Constant.NO)) {
//            //插入redis queue 并获取序号
//            int no = cacheService.unRepeatQueue(CANDY_KIDS_QUEUE + "_" + candyBoxId, userId.toString());
//            if (no <= 0) {
//                throw new IMRuntimeException(IMExceptionEnum.GET_CANDY_REPEAT);
//            }
//            if (no <= candyBox.getUserNum()) {
//                if (candyBox.getUserNum().equals(no)) {
//                    candyBox.setStatus(Constant.YES);
//                    candyBoxManager.updateById(candyBox);
//                    //设置队列key失效时间
//                    cacheService.expireUnRepeatQueue(CANDY_KIDS_QUEUE + "_" + candyBoxId, 30);
//                }
//                Boolean isGot = candyKidsRecordManager.updateUserIdByBoxIdAndNo(userId, candyBox.getId(), no);
//                if (isGot) {
//                    //增加金币
//                    CandyKidsRecord candyKidsRecord = candyKidsRecordManager.getOneByBoxIdAndNo(candyBoxId, no);
//                    GoldRedPacketReq goldRedPacketReq = new GoldRedPacketReq();
//                    goldRedPacketReq.setType(GoldWithHoldEnum.RED_PACKET.withHoldType);
//                    goldRedPacketReq.setOrderNo(candyKidsRecord.getBoxId().toString());
//                    goldRedPacketReq.setToUid(candyKidsRecord.getUserId());
//                    goldRedPacketReq.setRedPacketNo(candyKidsRecord.getId().toString());
//                    goldRedPacketReq.setAmount(candyKidsRecord.getCandyNum().intValue());
//                    Result result = goldApi.goldRedWars(goldRedPacketReq);
//                    if (! result.getCode().equals(Result.SUCCESS)) {
//                        logger.error("红包金币增加失败：{}", result.getMessage());
//                    }
//                }
//            }
//        }
//        return getCandyBoxDetail(candyBox.getId());
//    }
//
//    @Override
//    public CandyBoxVO getCandyBoxDetail(Long candyBoxId) {
//        CandyBox candyBox = candyBoxManager.getById(candyBoxId);
//        CandyBoxDTO candyBoxDTO = new CandyBoxDTO(candyBox);
//        CandyBoxVO candyBoxVO = candyBoxDTO.getCandyBoxVO();
//        List<CandyKidsRecord> candyKidsList = candyKidsRecordManager.listByBoxIdAndStatus(candyBoxId, Constant.YES);
//        List<CandyKidsVO> kidsList = Lists.newArrayList();
//        List<Long> userIdList = candyKidsList.stream().map(CandyKidsRecord::getUserId).collect(Collectors.toList());
//        BatchImGetUserReq req = new BatchImGetUserReq();
//        req.setUids(userIdList);
//        Result<List<ImGetUserInfo>> listResult = imUserCentreApi.batchImGetUserInfo(req);
//        HashMap<Long, ImGetUserInfo> userInfoMap = Maps.newHashMap();
//        if (listResult.getCode().equals(Result.SUCCESS)) {
//            listResult.getData().forEach(userInfo -> userInfoMap.put(userInfo.getUid(), userInfo));
//        }
//        candyKidsList.forEach(candyKidsRecord -> {
//            CandyKidsVO vo = new CandyKidsVO();
//            if (userInfoMap.containsKey(candyKidsRecord.getUserId())) {
//                vo.setLogo(userInfoMap.get(candyKidsRecord.getUserId()).getLogo());
//                vo.setUsername(userInfoMap.get(candyKidsRecord.getUserId()).getUsername());
//            }
//            vo.setUserId(candyKidsRecord.getUserId());
//            vo.setCandyType(candyKidsRecord.getCandyType());
//            vo.setCandyNum(candyKidsRecord.getCandyNum());
//            kidsList.add(vo);
//        });
//        candyBoxVO.setCandyKidsList(kidsList);
//        return candyBoxVO;
//    }
}
